package com.fot.config;

import com.fot.core.listener.RedisMQListener;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
public class QueueData {

    private String topic;

    private int taskId;

    private volatile String message;

    private final CopyOnWriteArrayList<RedisMQListener<?>> listeners;

    public QueueData(String topic) {
        this.topic = topic;
        listeners = new CopyOnWriteArrayList<>();
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public int getTaskId() {
        return taskId;
    }

    public void setTaskId(int taskId) {
        this.taskId = taskId;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void addListener(RedisMQListener<?> listener) {
        if (null == listener) {
            throw new IllegalArgumentException("listener is null");
        }
        if (listeners.addIfAbsent(listener)) {
            log.info("[{}] [add-listener] ok, topic={}", topic,
                    listeners.size());
        }
    }

    public void notifyListener() {
        for (RedisMQListener<?> listener : listeners) {
            listener.processMessage(message);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        QueueData queueData = (QueueData) o;
        return Objects.equals(topic, queueData.topic);
    }

    @Override
    public int hashCode() {
        return Objects.hash(topic);
    }
}
